<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 新增商品分类 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddCategoryDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 分类表格
        :data(设置数据源) :columns(设置表格中列配置信息) :selection-type(是否有复选框)
        :expand-type(是否展开数据) show-index(是否设置索引列) index-text(设置索引列头)
      border(是否添加纵向边框) :show-row-hover(是否鼠标悬停高亮)-->
      <el-row>
        <tree-table
          :data="categories"
          :columns="columns"
          :selection-type="false"
          :expand-type="false"
          show-index
          index-text="#"
          border
          :show-row-hover="false"
        >
          <!-- 是否有效区域， 设置对应的模板列： slot="isok"(与columns中设置的template一致) -->
          <template slot="isok" slot-scope="scope">
            <i class="el-icon-success" v-if="!scope.row.cat_deleted" style="color: skyblue;"></i>
            <i class="el-icon-error" v-else style="color:red"></i>
          </template>
          <!-- 排序插槽 -->
          <template slot="order" slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag size="mini" v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
            <el-tag size="mini" v-else-if="scope.row.cat_level === 2" type="warning">三级</el-tag>
          </template>
          <!-- 操作插槽 -->
          <template slot="opt" slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditCategoryDialog(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="showDeleteCategoryConfirm(scope.row)"
            >删除</el-button>
          </template>
        </tree-table>
      </el-row>
      <!-- 分页信息栏 -->
      <el-row>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryInfo.pagenum"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-row>
    </el-card>
    <!-- 添加商品分类弹出框 -->
    <el-dialog
      title="添加分类面板"
      :visible.sync="addCategoryDialogVisible"
      width="50%"
      @close="addCategoryDialogClose"
    >
      <el-form
        :model="addCategoryForm"
        ref="addCategoryRef"
        label-width="80px"
        :rules="categoryRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <!-- expandTrigger='hover'(鼠标悬停触发级联) v-model(设置级联菜单绑定数据) :options(指定级联菜单数据源)  :props(用来配置数据显示的规则) clearable(提供“X”号完成删除文本功能) change-on-select(是否可以选中任意一级的菜单)-->
          <el-cascader
            clearable
            filterable
            v-model="selectKeys"
            :options="parentCategories"
            :props="addCategoryProps"
            change-on-select
            @change="parentCategoryChange"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类弹出框 -->
    <el-dialog
      title="编辑商品分类信息"
      :visible.sync="editCategoryDialogVisible"
      width="50%"
      @close="editCategoryDialogClose"
    >
      <el-form
        :model="editCategoryForm"
        ref="editCategoryRef"
        label-width="80px"
        :rules="categoryRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <el-input v-model="editCategoryForm.cat_id" disabled></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategory">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categories: [],
      queryInfo: {
        type: 3,
        pagesize: 5,
        pagenum: 1
      },
      total: 0,
      columns: [
        { label: "分类名称", prop: "cat_name" },
        // type:'template'(将该列设置为模板列)，template:'isok'(设置该列模板的名称为isok)
        { label: "是否有效", prop: "", type: "template", template: "isok" },
        { label: "排序", prop: "", type: "template", template: "order" },
        { label: "操作", prop: "", type: "template", template: "opt" }
      ],
      addCategoryDialogVisible: false,
      addCategoryForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      categoryRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      parentCategories: [],
      addCategoryProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
        // checkStrictly: "false"
      },
      selectKeys: [],
      // 编辑分类
      editCategoryDialogVisible: false,
      editCategoryForm: {
        cat_name: "",
        cat_id: ""
      }
    };
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      this.categories = res.data.result;
      this.total = res.data.total;
    },
    async getParentCategories() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级商品分类列表失败");
      }
      this.parentCategories = res.data;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCategories();
    },
    handleCurrentChange(current) {
      this.queryInfo.pagenum = current;
      this.getCategories();
    },
    // 弹出删除商品分类确认框
    async showDeleteCategoryConfirm(category) {
      const result = await this.$confirm(
        "此操作将永久删除此商品分类且不可恢复，是否确认",
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }
      );
      if (result !== "confirm") {
        return this.$message.info("操作已取消");
      }
      this.deleteCategoryById(category.cat_id);
      // this.removeCategoryFrom(this.categories, category);
    },
    // 删除商品分类
    async deleteCategoryById(id) {
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除商品分类失败");
      }
      this.$message.success("删除商品分类成功");
      this.getCategories();
    },
    // 未深度监听，无法达成删除分类后不折叠
    removeCategoryFrom(node, category) {
      const index = node.children.findIndex(
        item => item.cat_id === category.cat_id
      );
      if (index < 0 && node.children) {
        node.children.forEach(child =>
          this.removeCategoryFrom(child, category)
        );
      } else {
        return node.children.splice(index, 1);
      }
    },
    parentCategoryChange() {
      // console.log(this.selectKeys);
      if (this.selectKeys.length > 0) {
        const length = this.selectKeys.length;
        this.addCategoryForm.cat_pid = this.selectKeys[length - 1];
        this.addCategoryForm.cat_level = this.selectKeys.length;
      } else {
        this.addCategoryForm.cat_pid = 0;
        this.addCategoryForm.cat_level = 0;
      }
    },
    // 添加商品分类
    showAddCategoryDialog() {
      this.getParentCategories();
      this.addCategoryDialogVisible = true;
    },
    addCategoryDialogClose() {
      this.$refs.addCategoryRef.resetFields();
      this.addCategoryForm.cat_pid = 0;
      this.addCategoryForm.cat_level = 0;
      this.selectKeys = [];
    },
    addCategory() {
      this.$refs.addCategoryRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCategoryForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品分类失败");
        }
        this.addCategoryDialogVisible = false;
        this.$message.success("添加商品分类成功");
        this.getCategories();
      });
    },
    // 编辑商品分类
    showEditCategoryDialog(category) {
      this.editCategoryForm.cat_name = category.cat_name;
      this.editCategoryForm.cat_id = category.cat_id;
      this.editCategoryDialogVisible = true;
    },
    editCategoryDialogClose() {
      this.editCategoryForm.cat_name = "";
      this.editCategoryForm.cat_id = "";
    },
    async editCategory() {
      const { data: res } = await this.$http.put(
        "categories/" + this.editCategoryForm.cat_id,
        this.editCategoryForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改商品分类名称失败");
      }
      this.editCategoryDialogVisible = false;
      this.$message.success("修改商品分类名称成功");
      this.getCategories();
    }
  },
  created() {
    this.getCategories();
  }
};
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 10px;
}

.el-pagination {
  margin-top: 10px;
}
</style>
